package BookManagement.controller;

import BookManagement.domain.*;
import BookManagement.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Autowired
    @Qualifier("bookService")
    private BookService bookService;

    @Autowired
    @Qualifier("borrowService")
    private BorrowService borrowService;

    @Autowired
    @Qualifier("purchaseService")
    private PurchaseService purchaseService;

    @Autowired
    @Qualifier("stockService")
    private StockService stockService;

    @RequestMapping("/index")
    public ModelAndView toIndex(){
        return new ModelAndView("admin/indexAdmin");
    }

    @RequestMapping("/allUser")
    public ModelAndView allUser(String pageNo, HttpSession hs){
        ModelAndView mav=new ModelAndView();
        User u =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(u==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        Page p=new Page(pageNo,10,userService.usercount());
        HashMap<String,Object>map=new HashMap<>();
        map.put("start",p.getStart());
        map.put("size",p.getPageSize());
        List<User> userList = userService.findAllUsers(map);
        mav.addObject("userList",userList);
        mav.addObject("page",p);
        mav.setViewName("/admin/users/allUsers");
        return mav;
    }

    @RequestMapping("/toUpdateUser")
    public ModelAndView toUpdateUser(String username,HttpSession hs){
        ModelAndView mav=new ModelAndView("admin/users/updateUser");
        User user = userService.findUserByUsername(username);
        hs.setAttribute("sex",user.getSex());
        mav.addObject("userSeeing",user);
        List<String> creditList = new ArrayList<>();
        creditList.add("A");
        creditList.add("B");
        creditList.add("C");
        creditList.add("D");
        creditList.add("E");
        mav.addObject("creditList",creditList);
        return mav;
    }

    @RequestMapping("/updateUser")
    public ModelAndView updateUser(String username,String credit,String balance){
        ModelAndView mav=new ModelAndView();
        User user = userService.findUserByUsername(username);
        user.setBalance(Double.parseDouble(balance));
        user.setCredit(credit);
        userService.updateUser(user);
        mav.addObject("username",username);
        mav.setViewName("/admin/users/updateSucc");
        return mav;
    }

    @RequestMapping("/delUser/{username}/{pagecurrent}")
    public ModelAndView delUser(@PathVariable("username") String username, @PathVariable("pagecurrent") String pageCurrent,HttpSession hs) throws IOException {
        User u = userService.findUserByUsername(username);
        String photoPath=hs.getServletContext().getRealPath(u.getPhoto());
        Path path = Paths.get(photoPath);
        Files.delete(path);
        userService.deleteUserByUsername(username);
        return new ModelAndView("redirect:/admin/allUser?pageNo="+pageCurrent);
    }

    @RequestMapping("/toAllBorrowing")
    public ModelAndView toAllBorrowing(String pageNo) throws ParseException {
        Page p=new Page(pageNo,10,borrowService.getTotalBorrowing());
        HashMap<String,Object>map=new HashMap<>();
        map.put("start",p.getStart());map.put("size",p.getPageSize());
        List<Borrow> borrowList = borrowService.searchAllBorrowingBook(map);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String now = df.format(new Date());
        for (int i=0; i<borrowList.size(); i++){
            String length = new Borrow().getTime(df.parse(now),df.parse(borrowList.get(i).getTimeStart()),borrowList.get(i).getLength());
            length = length.substring(0,length.length()-1);
            if (Integer.valueOf(length) < 0){
                length = "超时 "+length.substring(1)+" 天";
            } else {
                length = "还剩 "+length+" 天";
            }
            borrowList.get(i).setLength(length);
        }
        ModelAndView mav=new ModelAndView();
        mav.addObject("borrowsList",borrowList);
        mav.addObject("page",p);
        mav.setViewName("admin/users/allBorrows");
        return mav;
    }

    @RequestMapping("/toAllPurchasing")
    public ModelAndView toAllPurchasing(String pageNo) throws ParseException{
        Page p=new Page(pageNo,10,borrowService.getTotalBorrowing());
        HashMap<String,Object>map=new HashMap<>();
        map.put("start",p.getStart());map.put("size",p.getPageSize());
        List<Purchase> purchaseList = purchaseService.findAllPurchase(map);
        ModelAndView mav=new ModelAndView();
        mav.addObject("purchaseList",purchaseList);
        mav.addObject("page",p);
        mav.setViewName("admin/users/allPurchases");
        return mav;
    }

    @RequestMapping("/toStocking")
    public ModelAndView toStocking(String pageNo){
        ModelAndView mav=new ModelAndView();
        int total=bookService.getTotalBooks();
        Page p=new Page(pageNo,10,total);
        HashMap<String,Object>map=new HashMap<>();
        map.put("start",p.getStart());map.put("size",p.getPageSize());
        List<Book> bookList = bookService.findAllBooks(map);
        mav.addObject("page",p);
        mav.addObject("bookList",bookList);
        mav.setViewName("admin/books/purchaseManage");
        return mav;
    }

    @RequestMapping("/displayStocking")
    public ModelAndView displayStocking(String pageNo){
        ModelAndView mav=new ModelAndView();
        HashMap<String,Object> map = new HashMap<String,Object>();
        Page p=new Page(pageNo,10,stockService.getTotalStocks(map));
        map.put("start",p.getStart());
        map.put("size", p.getPageSize());
        List<Stock> stockList = stockService.findStocks(map);
        mav.addObject("stockList", stockList);
        mav.addObject("page", p);
        mav.setViewName("admin/books/displayStocking");
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "/updateStocking",method = RequestMethod.POST)
    public String updateStocking(@RequestBody List<Stock> list){
        System.out.println(list);
        Boolean flag=false;
        for (int i=0;i<list.size();i++){
            if (!list.get(i).getAddress().equals("") && list.get(i).getCounts()!=0){
                list.get(i).setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
                stockService.addStocking(list.get(i));
                Book book = bookService.findByISBN(list.get(i).getBookISBN());
                book.setBookCounts(book.getBookCounts()+list.get(i).getCounts());
                bookService.updateBook(book);
                flag=true;
            }
        }
        if(flag)return "success";else return "fail";
    }
}
